package com.ziyun.pop.modules.messageCenter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziyun.pop.common.e.message.MessTypeEnum;
import com.ziyun.pop.common.e.message.MessageStatusEnum;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.messageCenter.dao.MessageCenterDao;
import com.ziyun.pop.modules.messageCenter.dto.MessageDto;
import com.ziyun.pop.modules.messageCenter.entity.MessageCenterEntity;
import com.ziyun.pop.modules.messageCenter.service.MessageCenterService;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessageCenterServiceImpl extends ServiceImpl<MessageCenterDao, MessageCenterEntity> implements MessageCenterService {

    @Autowired
    private MessageCenterService messageCenterService;

    @Override
    public R getUserMessageData(Long sellerId) {
        List<MessageCenterEntity> messageList = baseMapper.queryUserMassageListBySellerId(sellerId);
        //找出留言列表中 客户给商户的留言;
        List<MessageCenterEntity> userMessageList = new ArrayList<>();
        for (MessageCenterEntity messageCenterEntity : messageList) {
            if (messageCenterEntity.getMessageType() == 1){
                userMessageList.add(messageCenterEntity);
            }
        }
        if (userMessageList.size() == 0 || null == userMessageList){
            return R.apiError(0,"当前无用户留言");
        }
        return R.apiOk(userMessageList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R leaveMessageToUser(MessageDto messageDto) {
        //通过消息id读取到当前留言,修改留言状态为:已读;
        MessageCenterEntity currentMessage = this.baseMapper.selectById(messageDto.getMessageId());
        currentMessage.setMessageStatus(MessageStatusEnum.READ.toInt());
        messageCenterService.save(currentMessage);

        //回复留言;
        MessageCenterEntity message = new MessageCenterEntity();

        message.setUserId(currentMessage.getUserId());
        message.setSellerId(UserUtils.getCurentUser().getSellerId());
        message.setMessageStatus(MessageStatusEnum.UNREAD.toInt());
        message.setMessageContent(messageDto.getMessageContent());
        message.setCreateTime(new Date());
        //判断留言类型;
        if (currentMessage.getMessageType() == 1){
            //设置留言类型;商户给用户留言;
            message.setMessageType(MessTypeEnum.MESSAGE_TO_USER.toInt());
        }else if (currentMessage.getMessageType() == 0){
            //设置留言类型;用户给商户留言;
            message.setMessageType(MessTypeEnum.MESSAGE_TO_SELLER.toInt());
        }

        //保存留言;
        messageCenterService.save(message);

        return R.ok().put("msg","回复成功");
    }
}
